package com.shuo.dsa.sort;

import java.util.Arrays;

/**
 * 选择排序: 选择最大的往后插入 (交换)
 * DSA-Deng: P81
 * selectMax + insertTail
 */
public class ShuoGGSelection {
    public static void main(String[] args) {
        int[] arrays = {2, 3, 1, 4, 3, 5, 1, 6, 1, 2, 3, 7, 2, 3};
        int tailIndex = arrays.length - 1;
        for (int i = 0; i < arrays.length; i++) {
            int maxIndex = selectMax(arrays, 0, arrays.length - i - 1);
            swap(arrays, maxIndex, tailIndex);
            tailIndex--;
        }
        System.out.println(Arrays.toString(arrays));
    }

    private static int selectMax(int[] target, int start, int end) {
        int max = target[start];
        int maxIndex = start;
        for (int i = start; i <= end; i++) {
            if (target[i] > max) {
                max = target[i];
                maxIndex = i;
            }
        }
        return maxIndex;
    }

    private static void swap(int[] target, int index1, int index2) {
        int temp = target[index1];
        target[index1] = target[index2];
        target[index2] = temp;
    }
}
